<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Qweas Bookstore - Control Panel</title>
    <link href="../css/ui.css" rel="stylesheet"/>
    <link href="../css/framework.css" rel="stylesheet"/>
    <link href="../css/admin.css" rel="stylesheet"/>
    <link href="../css/font-awesome.min.css" rel="stylesheet"/>

    <!-- Import jQuery, Bootstrap and DataTables -->
    <link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/DataTables-1.10.16/css/dataTables.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/FixedHeader-3.1.3/css/fixedHeader.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/KeyTable-2.3.2/css/keyTable.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/Responsive-2.2.1/css/responsive.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/Scroller-1.4.4/css/scroller.bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="../assets/Select-1.2.5/css/select.bootstrap.min.css"/>

    <script type="text/javascript" src="../js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="../js/bootstrap.min.js"></script>
    <script type="text/javascript" src="../assets/DataTables-1.10.16/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="../assets/DataTables-1.10.16/js/dataTables.bootstrap.min.js"></script>
    <script type="text/javascript" src="../assets/FixedHeader-3.1.3/js/dataTables.fixedHeader.min.js"></script>
    <script type="text/javascript" src="../assets/KeyTable-2.3.2/js/dataTables.keyTable.min.js"></script>
    <script type="text/javascript" src="../assets/Responsive-2.2.1/js/dataTables.responsive.min.js"></script>
    <script type="text/javascript" src="../assets/Responsive-2.2.1/js/responsive.bootstrap.min.js"></script>
    <script type="text/javascript" src="../assets/Scroller-1.4.4/js/dataTables.scroller.min.js"></script>
    <script type="text/javascript" src="../assets/Select-1.2.5/js/dataTables.select.min.js"></script>

    <!-- Validator -->
    <script type="text/javascript" src="../js/validator.min.js"></script>
    <script>
        const BOOKID = "BookId", TITLE = "BookName", PICTURE = "Picture", AUTHOR = "Author",
            PRICE = "Price", DESC = "Description", STOCK = "Stock";
        var currentSelectedRowData = null, table;
    </script>
</head>
<body>
<div id="header">
    <img id="imgLogo" style="margin-left: 10px" src="../images/bookstore_logo.png"/>
    <div id="navbar" align="right">
        <!-- Control buttons -->
        <div id="toggleBookMgr" class="ctrl-panel-item ctrl-active font-navbar ctrl-left">
            <a href="#"><i class="fa fa-book font-navbar"></i>&nbsp;Books</a>
        </div>
        <div id="toggleUserMgr" class="ctrl-panel-item font-navbar">
            <a href="usermgr.jsp"><i class="fa fa-users font-navbar"></i>&nbsp;Customers</a>
        </div>
        <div id="toogleCommentMgr" class="ctrl-panel-item font-navbar">
            <a href="commentmgr.jsp"><i class="fa fa-comment font-navbar"></i>&nbsp;Comments</a>
        </div>
        <div id="toggleOrderMgr" class="ctrl-panel-item font-navbar ctrl-right">
            <a href="ordermgr.jsp"><i class="fa fa-dollar font-navbar"></i>&nbsp;Orders</a>
        </div>&nbsp;&nbsp;&nbsp;
        <!-- Logout -->
        <div id="btnSignout" class="navbar_item div-button font-navbar">
            <i class="fa fa-sign-out font-navbar"></i>&nbsp;EXIT
        </div>
    </div>
</div>
<div id="content">
    <!-- CONTENTS -->
    <div class="bs-container">
        <!-- Left part -->
        <div class="bs-container-left">
            <!-- Book Details -->
            <div id="divDetails" class="group-panel book-details-panel">
                <div class="group-panel-header"><i class="fa fa-eye font-panel-header"></i>&nbsp;BOOK DETAILS</div>
                <img id="ImgBookCover" class="book-cover-container" src="../images/cover_unknown.jpg"/>
                <div id="ImgUploadOverlay">
                    <input id="btnChangeCover" type="button" value="Change Cover" />
                </div>
            </div>

            <!-- Operation Panel -->
            <div class="group-panel operation-panel" style="margin-top: 10px">
                <div class="group-panel-header"><i class="fa fa-gear font-panel-header"></i>&nbsp;OPERATIONS</div>
                <div id="btnAddBook" class="operation-panel-item" style="margin-top: 5px">
                    <i class="fa fa-plus green small-icon"></i>&nbsp;Add New Book...
                </div>
                <div id="btnEditBook" class="operation-panel-item">
                    <i class="fa fa-edit small-icon"></i>&nbsp;Edit Selected Book
                </div>
                <div id="btnMarkUnavailable" class="operation-panel-item">
                    <i class="fa fa-warning yellow small-icon"></i>&nbsp;Mark as Unavailable
                </div>
                <hr style="margin-top: 5px; margin-bottom: 5px;"/>
                <div id="btnDeleteBook" class="operation-panel-item">
                    <i class="fa fa-remove red small-icon"></i>&nbsp;Remove Selected
                </div>
            </div>
        </div>
        <div class="bs-container-right">
            <div class="group-panel booklist-panel">
                <div class="group-panel-header"><i class="fa fa-search font-panel-header"></i>&nbsp;BOOK MANAGEMENT
                    <span style="float: right">
                        <input type="checkbox" value="" id="chkMultiSelectMode" style="padding: 0;"/>
                        <label for="chkMultiSelectMode">Enable Multi-Selection</label>
                    </span>
                </div>
                <!-- Alert Area -->
                <div class="group-panel-alerts">
                    <!-- success -->
                    <div class="alert alert-success group-panel-alert hidden" id="alert-success">
                        <button type="button" class="close"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                        <span></span>
                    </div>
                    <!-- error -->
                    <div class="alert alert-danger group-panel-alert hidden" id="alert-error">
                        <button type="button" class="close"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                        <span></span>
                    </div>
                </div>
                <div id="table-container">
                    <table id="bookTable" class="table table-striped table-bordered table-hover no-cursor" style="width: 100%">
                        <thead>
                        <tr>
                            <th>BookID</th> <!-- hidden -->
                            <th>Title</th>
                            <th>Picture</th> <!-- hidden -->
                            <th>Author</th>
                            <th>Price</th>
                            <th>Description</th> <!-- hidden -->
                            <th>Stock</th>
                        </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div id="footer" align="center">
        <p style="font-size: 13px; color: lightgray;">
            © 2018 Qweas Bookstore, Zhang Wenqiang, Wu Jiatian, Ethan Phung, Andrew Lu and Eric Shuai. All rights
            reserved.</p>
    </div>
</div>

<!-- Modal Forms -->
<div id="modalNewBook" class="modal fade" tabindex="-4" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"
                        onclick="addbook_form_reset()">&times;</button>
                <h4 class="modal-title no-cursor">Add New Book</h4>
            </div>
            <form class="form-horizontal" action="../AddBookServlet" enctype="multipart/form-data" method="post" id="addbook_form"
                  role="form" data-toggle="validator">
                <div class="modal-body">
                    <div class="form-group has-feedback">
                        <!-- Book title -->
                        <label class="col-md-4 control-label">Book Title</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-book"></i></span>
                                <input name="book_title" id="book_title" placeholder="Book Title" class="form-control" type="text"
                                       required/>
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>

                    <div class="form-group has-feedback">
                        <!-- Book Cover -->
                        <label class="col-md-4 control-label">Cover</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <label class="input-group-btn">
                                    <span class="btn btn-primary">
                                        Browse&hellip; <input type="file" id="book_cover" style="display: none;" accept=".jpg,.png,.bmp" />
                                    </span>
                                </label>
                                <input type="text" name="book_cover" class="form-control" readonly required/>
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>

                    <div class="form-group has-feedback">
                        <!-- Author -->
                        <label class="col-md-4 control-label">Author</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                                <input name="book_author" id="book_author" placeholder="Book Author" class="form-control" type="text"
                                       required/>
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>

                    <div class="form-group has-feedback">
                        <!-- Price -->
                        <label class="col-md-4 control-label">Price</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-yen"></i></span>
                                <input name="book_price" id="book_price" placeholder="Book Price (Digits only)"
                                       min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100"
                                       class="form-control" type="number" required/>
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>

                    <div class="form-group has-feedback">
                        <!-- Stock -->
                        <label class="col-md-4 control-label">Stock</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
                                <input name="book_stock" id="book_stock" placeholder="Stock (Digits only)"
                                       min="0" step="1" data-number-to-fixed="2" data-number-stepfactor="100"
                                       class="form-control" type="number" required/>
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>

                    <div class="form-group">
                        <!-- Desc. -->
                        <label class="col-md-4 control-label">Description</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                                <textarea name="book_desc" id="book_desc" placeholder="Description goes here..." class="form-control"
                                          maxlength="255"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"
                            onclick="addbook_form_reset();">Close</button>
                    <button type="submit" class="btn btn-primary">Add</button>
                </div>
            </form>
            <script>
                // Add book form submit action handling
                $('#addbook_form').submit(function (){
                	
                	var formData = new FormData();
                    formData.append("bookName",$('#book_title').val());
                    formData.append("picture",document.getElementById("book_cover").files[0]);
                    formData.append("author",$('#book_author').val());
                    formData.append("price",$('#book_price').val());
                    formData.append("description",$('#book_desc').val());
                    formData.append("stock",$('#book_stock').val());
                    
                    $.ajax({
                        data:formData,
                        type: $(this).attr('method'),
                        url: $(this).attr('action'),
                        cache: false,//上传文件无需缓存
                        processData: false,//用于对data参数进行序列化处理 这里必须false
                        contentType: false, //必须
                        success: function(response) {
                            console.log("Add book AJAX: " + response);
                            $('#modalNewBook').modal('hide');
                            addbook_form_reset();
                            if(response === "addBookSuccess") {
                                // Refresh the table
                                ReloadBookTable();
                                PushAlert("success", "Success", "Added '" + $('#book_title').val() + "'!");
                            } else
                                PushAlert("error", "Error", "Failed to add book. An error occurred during the action.");
                        },
                        error: function (xhr, desc, err) {
                            $('#modalNewBook').modal('hide');
                            addbook_form_reset();
                            PushAlert("error", "Error", "An error occurred while communicating with the server.");
                        }
                    });
                    return false;
                });
            </script>
        </div>
    </div>
</div>

<div id="modalEditBook" class="modal fade" tabindex="-3" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title no-cursor">Edit '%BOOK_TITLE%'</h4>
            </div>
            <form class="form-horizontal" action="../ChangeBookInfoServlet" method="post" id="editbook_form"
                  role="form" data-toggle="validator">
                <div class="modal-body">
                    <div class="form-group has-feedback">
                        <!-- Book title -->
                        <label class="col-md-4 control-label">Book Title</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-book"></i></span>
                                <input name="book_edit_title" id="book_edit_title" placeholder="Book Title" class="form-control" type="text"
                                       required/>
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>

                    <div class="form-group has-feedback">
                        <!-- Author -->
                        <label class="col-md-4 control-label">Author</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                                <input name="book_edit_author" id="book_edit_author" placeholder="Book Author" class="form-control" type="text"
                                       required/>
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>

                    <div class="form-group has-feedback">
                        <!-- Price -->
                        <label class="col-md-4 control-label">Price</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-yen"></i></span>
                                <input name="book_edit_price" id="book_edit_price" placeholder="Book Price (Digits only)"
                                       min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100"
                                       class="form-control" type="number" required/>
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>

                    <div class="form-group has-feedback">
                        <!-- Stock -->
                        <label class="col-md-4 control-label">Stock</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
                                <input name="book_edit_stock" id="book_edit_stock" placeholder="Stock (Digits only)"
                                       min="0" step="1" data-number-to-fixed="2" data-number-stepfactor="100"
                                       class="form-control" type="number" required/>
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>

                    <div class="form-group">
                        <!-- Desc. -->
                        <label class="col-md-4 control-label">Description</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                                <textarea name="book_edit_desc" id="book_edit_desc" placeholder="Description goes here..." class="form-control"
                                          maxlength="255"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Edit</button>
                </div>
            </form>
            <script>
                // Edit book form submit action handling
                $('#editbook_form').submit(function (){
                    $.ajax({
                        data: {
                            bookId: currentSelectedRowData[BOOKID],
                            bookName: $('#book_edit_title').val(),
                            author: $('#book_edit_author').val(),
                            price: $('#book_edit_price').val(),
                            description: $('#book_edit_desc').val(),
                            stock: $('#book_edit_stock').val()
                        },
                        type: $(this).attr('method'),
                        url: $(this).attr('action'),
                        success: function(response) {
                            console.log("Edit book AJAX: " + response);
                            $('#modalEditBook').modal('hide');
                            if(response === "UpdateBookInfoSuccess") {
                                // Refresh the table
                                ReloadBookTable();
                                PushAlert("success", "Success", "Edited '" + $('#book_edit_title').val() + "'.");
                            } else
                                PushAlert("error", "Error", "Failed to edit book. An error occurred during the action.");
                        },
                        error: function (xhr, desc, err) {
                            $('#modalEditBook').modal('hide');
                            PushAlert("error", "Error", "An error occurred while communicating with the server.");
                        }
                    });
                    return false;
                });
            </script>
        </div>
    </div>
</div>

<div id="modalChangeCover" class="modal fade" tabindex="-2" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"
                        onclick="changecover_form_reset()">&times;
                </button>
                <h4 class="modal-title">Change cover for %BOOK_NAME%</h4>
            </div>
            <form class="form-horizontal" action="../ChangePictureServlet" method="POST" id="changecover_form" role="form"
            	enctype="multipart/form-data" data-toggle="validator">
                <div class="modal-body">
                    <div class="form-group has-feedback">
                        <!-- Book Cover -->
                        <label class="col-md-4 control-label">New Cover</label>
                        <div class="col-md-6 inputGroupContainer">
                            <div class="input-group">
                                <label class="input-group-btn">
                                <span class="btn btn-primary">
                                    Browse&hellip; <input type="file" id="book_new_cover" style="display: none;" accept=".jpg,.png,.bmp" required/>
                                </span>
                                </label>
                                <input type="text" name="book_new_cover" class="form-control" readonly required />
                            </div>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"
                            onclick="changecover_form_reset();">Cancel
                    </button>
                    <button type="submit" class="btn btn-primary">Upload</button>
                </div>
            </form>
            <script>
                $('#changecover_form').submit(function (e) {
                    e.preventDefault();
                    //console.log("change_cover:" + currentSelectedRowData[BOOKID]);
                    var formData = new FormData();
                    formData.append("bookId", currentSelectedRowData[BOOKID]);
                    formData.append("picture",document.getElementById("book_new_cover").files[0]);
                    
                    $.ajax({
                        data: formData,
                        processData: false,
                        contentType: false,
                        cache: false,//上传文件无需缓存
                        enctype: 'multipart/form-data',
                        type: $(this).attr('method'),
                        url: $(this).attr('action'),
                        success: function (response) {
                            $('#modalChangeCover').modal('hide');
                            if (response === "ChangePictureSuccess") {
                                PushAlert("success", "Success", "Cover picture changed successfully.");
                            } else
                                PushAlert("error", "Error", "Failed to change cover. Please try again later.");
                            ReloadBookTable();
                        },
                        error: function (xhr, desc, err) {
                            $('#modalChangeCover').modal('hide');
                            PushAlert("error", "Error", "An error occurred while communicating with the server.");
                        }
                    });
                });
            </script>
        </div>
    </div>
</div>

<!-- Confirm Dialogue -->
<div class="modal fade" id="confirm-dialogue" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title no-cursor">%CONFIRMATION_TITLE%</h4>
            </div>
            <div class="modal-body">
                <p>%CONTENT%</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal" type="button">Cancel</button>
                <button class="btn" id="confirm-button" type="button">%BUTTON_TEXT%</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).on('change', ':file', function() {
        let input = $(this),
            label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
        input.trigger('fileselect', [1, label]);
        $('#changecover_form').validator('validate');
    });
    document.getElementById('book_cover').addEventListener('change', ProcessFileSelectEvent, false);
    document.getElementById('book_new_cover').addEventListener('change', ProcessFileSelectEvent, false);

    // Hide all alerts
    $('.group-panel-alert').hide().removeClass('hidden'); // to prevent weird flash

    $(document).ready(function() {
        table = $('#bookTable').DataTable({
            paging: true, autoWidth: true, ordering: true,
            columns: [
                { data: 'BookId' },
                { data: 'BookName' },
                { data: 'Picture' },
                { data: 'Author' },
                { data: 'Price' },
                { data: 'Description' },
                { data: 'Stock' }
            ],
            columnDefs: [
                {
                    "targets": [0], // BookID
                    "visible": false,
                    "searchable": true
                },
                {
                    "targets": [2], // Picture
                    "visible": false,
                    "searchable": false
                },
                {
                    "targets": [5], // Desc.
                    "visible": false,
                    "searchable": true
                }
            ],
            ajax: {
                url: "../QueryAllBookServlet",
                type: "POST",
                dataSrc: ''
            }
        });

        // Bind table click event
        $('#bookTable tbody').on('click', 'tr', function () {
            let isMultiSelectMode = $('#chkMultiSelectMode').prop('checked');

            currentSelectedRowData = table.row(this).data();
            if(isMultiSelectMode) {
                $(this).toggleClass('selected');
            } else {
                // Single selection mode
                if($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    currentSelectedRowData = null;
                } else {
                    table.$('tr.selected').removeClass('selected');
                    $(this).addClass('selected');
                }
            }
            // Disable Upload functionality when no row selected or multi-select mode is on.
            EnableUploadOverlay((currentSelectedRowData == null) || isMultiSelectMode);
            SetImage($("#ImgBookCover"), currentSelectedRowData != null ? "../"+currentSelectedRowData[PICTURE] : null);
        });

        // Bind customized file upload event
        $(":file").on('fileselect', function(event, numFiles, label) {
            let input = $(this).parents('.input-group').find(':text');
            // Nothing to do at this moment...
            input.val(label);
        });

        // Checkbox event - clear all selection if select mode changed to single
        $('#chkMultiSelectMode').change(function(){
            if(!this.checked && table.rows('.selected').data().length > 1) {
                table.$('tr.selected').removeClass('selected');
                SetImage($('#ImgBookCover'), "../images/cover_unknown.jpg");
                EnableUploadOverlay(true);
                currentSelectedRowData = null;
            }
        });

        // Bind click event for left operation panel
        $("#btnAddBook").click(function() {
            $('#modalNewBook').modal('show');
        });
        $('#btnChangeCover').click(function() {
            $('#modalChangeCover').modal('show');
        });
        $('#btnDeleteBook').click(function() {
            let isSingleMode = !$('#chkMultiSelectMode').prop('checked');
            let rows = null, notice;

            if(isSingleMode && currentSelectedRowData == null) {
                PushAlert("error", "Oops", "No book to delete.");
                return;
            }
            if(!isSingleMode) {
                rows = table.rows('.selected').data();
                if(rows.length < 1) {
                    PushAlert("error", "Oops", "No book to delete.");
                    return;
                }
            }
            notice = isSingleMode ? "'" + currentSelectedRowData[TITLE] + "'" : "these " + rows.length + " book(s)";
            ShowConfirm("Delete Confirmation", "Are you sure to delete " + notice + "?",
                "Delete", "btn-danger", "Callback_DeleteBooks");
        });
        $('#btnMarkUnavailable').click(function() {
            let isSingleMode = !$('#chkMultiSelectMode').prop('checked');
            let rows = null, notice;

            if(isSingleMode && currentSelectedRowData == null) {
                PushAlert("error", "Oops", "No book selected to perform this action.");
                return;
            }
            if(!isSingleMode) {
                rows = table.rows('.selected').data();
                if(rows.length < 1) {
                    PushAlert("error", "Oops", "No book selected to perform this action.");
                    return;
                }
            }
            notice = isSingleMode ? "'" + currentSelectedRowData[TITLE] + "'" : "these " + rows.length + " book(s)";
            ShowConfirm("Stock Status Confirmation", "Are you sure to mark " + notice + " as unavailable?",
                "Proceed", "btn-danger", "Callback_MarkBooksUnavailable");
        });
        $('#btnEditBook').click(function() {
            let isSingleMode = !$('#chkMultiSelectMode').prop('checked');

            if(isSingleMode) {
                if(currentSelectedRowData != null) {
                    $('#modalEditBook').find('.modal-title').text("Edit '" + currentSelectedRowData[TITLE] + "'");
                    $('#book_edit_author').val(currentSelectedRowData[AUTHOR]);
                    $('#book_edit_desc').val(currentSelectedRowData[DESC]);
                    $('#book_edit_stock').val(currentSelectedRowData[STOCK]);
                    $('#book_edit_title').val(currentSelectedRowData[TITLE]);
                    $('#book_edit_price').val(currentSelectedRowData[PRICE]);
                    $('#modalEditBook').modal('show');
                } else
                    PushAlert("error", "Error", "No book to edit.");
            } else
                PushAlert("error", "Error", "You can only edit one book each time.");
        });
        $('#btnSignout').click(function () {
        	window.location.replace("../login.jsp");
        });
    });

    var __base64Data = null;
    function ProcessFileSelectEvent(event) {
        let file = event.target.files[0];
        let reader = null;

        if(!file.type.match('image.*'))
            return; // skip if it's not an image
        reader = new FileReader();
        reader.onload = (function(file) {
            return function(e) {
                //console.log(e.target.result);
                //__base64Data = e.target.result;
                __base64Data = reader.result;
            }
        })(file);
        //reader.readAsDataURL(file);
        reader.readAsBinaryString(file);
    }

    function GetCurrentBase64Data() {
        let result = __base64Data;
        __base64Data = null;
        return result;
    }

    function PushAlert(type, title, message) {
        let object = (type === "success") ? $('#alert-success') : $('#alert-error');
        let span = object.children('span');
        let timer, timeout = 3000; // 3s

        span.html("<strong>" + title + "!</strong>&nbsp;" + message);
        object.appendTo('.group-panel-alerts');
        object.slideDown();

        // Set timeout
        clearTimeout(timer);
        timer = window.setTimeout(function(){
            object.slideUp();
            span.innerHTML = ""; // clear
        }, timeout);
    }

    function ShowConfirm(title, content, btntxt, btnclass, callback_funcname) {
        let dialogue = $('#confirm-dialogue');
        let btn = $('#confirm-button');

        dialogue.find('.modal-title').text(title);
        dialogue.find('.modal-body').children('p').html(content);
        btn.text(btntxt);
        btn.addClass(btnclass);
        btn.unbind('click');
        btn.attr('onClick', callback_funcname + "('" + btnclass + "', '#confirm-dialogue', '#confirm-button')");
        dialogue.modal('show');
    }

    function SetImage(obj, url) {
        let img = new Image();

        img.onerror = function() {
            obj.attr("src", "../images/cover_unknown.jpg");
            if(url != null)
                console.log("Invalid image reference: " + url);
        };
        img.onload = function() { obj.attr("src", url); };
        img.src = url;
        console.log("loading cover: " + url);
    }

    function ReloadBookTable() {
        EnableUploadOverlay(true); // disable upload functionality
        SetImage($('#ImgBookCover'), "../images/cover_unknown.jpg");
        currentSelectedRowData = null;
        table.ajax.reload();
    }

    function EnableUploadOverlay(disable) {
        $('#ImgUploadOverlay').css("display", disable ? "none" : "block");
        $('#ImgUploadOverlay').css("visibility", disable ? "hidden" : "visible");
        if(currentSelectedRowData != null)
            $('#modalChangeCover .modal-title').text("Change cover for '"+currentSelectedRowData[TITLE]+"'");
    }

    function addbook_form_reset() {
        $('#addbook_form').find(':file').val("");
        $('#addbook_form').validator('validate');
        document.getElementById("addbook_form").reset();
    }

    function changecover_form_reset() {
        $('#changecover_form').find(':file').val("");
        $('#changecover_form').validator('validate');
        document.getElementById("changecover_form").reset();
    }

    function DeleteSingleBook(bookid, cb_args, success_cb, error_cb) {
        $.ajax({
            url: "../UpdateBookStockServlet",
            type: "post",
            data: { bookId: bookid, stock: -1 },
            success: function(response) {
                if(response === "UpdateBookStockSuccess") {
                    if(success_cb != null)
                        success_cb(bookid, cb_args);
                    else
                        PushAlert("success", "Success", "Selected book (id:" + bookid + ") deleted.");
                } else {
                    if(error_cb != null)
                        error_cb(bookid, cb_args);
                    else
                        PushAlert("error", "Error", "Failed to delete the selected book (id=" + bookid + ").");
                }
            },
            error: function(xhr, desc, err) {
                PushAlert("error", "Error", "Communication failure. Please try again later.");
            }
        });
    }

    function MarkSingleBookUnavailable(bookid, cb_args, success_cb, error_cb) {
        $.ajax({
            url: "../UpdateBookStockServlet",
            type: "post",
            data: { bookId: bookid, stock: 0 },
            success: function(response) {
                if(response === "UpdateBookStockSuccess") {
                    if(success_cb != null)
                        success_cb(bookid, cb_args);
                    else
                        PushAlert("success", "Success", "Marked book (id:" + bookid + ") as unavailable successfully.");
                } else {
                    if(error_cb != null)
                        error_cb(bookid, cb_args);
                    else
                        PushAlert("error", "Error", "Failed to change status for book (id=" + bookid + ").");
                }
            },
            error: function(xhr, desc, err) {
                PushAlert("error", "Error", "Communication failure. Please try again later.");
            }
        });
    }

    function Callback_DeleteBooks(classname, objname, btnobjname) {
        let isSingleMode = !$('#chkMultiSelectMode').prop('checked');
        let title, bookid;

        $('#confirm-dialogue').modal('hide');
        if(isSingleMode && currentSelectedRowData != null) {
            title = currentSelectedRowData[TITLE];
            bookid = currentSelectedRowData[BOOKID];
            DeleteSingleBook(bookid, title, function (bookid, cb_args) {
                PushAlert("success", "Success", "'" + cb_args + "' deleted successfully.");
            }, null);
        } else {
            let rows = table.rows('.selected').data();
            let pass = 0;

            for(let i = 0; i < rows.length; i++) {
                DeleteSingleBook(rows[i][BOOKID], null, function() { pass++; }, null);
            }
            if(rows.length > 0) {
                if(pass === rows.length)
                    PushAlert("success", "Success", "Deleted " + pass + " book(s) successfully.");
                else {
                    let failures = rows.length - pass;
                    PushAlert("error", "Error", "Deleted " + pass + " book(s) successfully but " + failures + " failed.");
                }
            }
        }
        ReloadBookTable();
        $(objname).modal('hide');
        $(btnobjname).removeClass(classname);
    }

    function Callback_MarkBooksUnavailable(classname, objname, btnobjname) {
        let isSingleMode = !$('#chkMultiSelectMode').prop('checked');
        let title, bookid;

        if(isSingleMode && currentSelectedRowData != null) {
            title = currentSelectedRowData[TITLE];
            bookid = currentSelectedRowData[BOOKID];
            MarkSingleBookUnavailable(bookid, title, function (bookid, cb_args) {
                PushAlert("success", "Success", "'" + cb_args + "' deleted successfully.");
            }, null);
        } else {
            let rows = table.rows('.selected').data();
            let pass = 0;

            for(let i = 0; i < rows.length; i++) {
                MarkSingleBookUnavailable(rows[i][BOOKID], null, function() { pass++; }, null);
            }
            if(rows.length > 0) {
                if(pass === rows.length)
                    PushAlert("success", "Success", "Changed stock status for " + pass + " book(s) successfully.");
                else {
                    let failures = rows.length - pass;
                    PushAlert("error", "Error", "Changed stock status for " + pass + " book(s) successfully but " + failures + " failed.");
                }
            }
        }
        ReloadBookTable();
        $(objname).modal('hide');
        $(btnobjname).removeClass(classname);
    }
</script>
</body>
</html>